#include <iostream>
#include <websocketpp/config/asio_no_tls.hpp>
 #include <websocketpp/server.hpp>
typedef websocketpp::server<websocketpp::config::asio> wsserver_t;
void http_callback(wsserver_t *srv,websocketpp::connection_hdl hdl){
wsserver_t::connection_ptr conn=srv->get_con_from_hdl(hdl);
std::cout<<"body:"<<conn->get_request_body()<<std::endl;
websocketpp::http::parser::request req=conn->get_request();
std::cout<<"method:"<<req.get_method()<<std::endl;
std::cout<<"uri:"<<req.get_uri()<<std::endl;
std::string body="<html><body><h1>hello world</h1></body></html>";
conn->set_body(body);
conn->append_header("Content-Type","text/html");
conn->set_status(websocketpp::http::status_code::ok);
}
void wsopen_callback(wsserver_t *srv,websocketpp::connection_hdl hdl){
 std::cout<<"websocket握手成功！"<<std::endl;
}
void wsclose_callback(wsserver_t *srv,websocketpp::connection_hdl hdl){
std::cout<<"websocket连接关闭"<<std::endl;
}
void wsmsg_callback(wsserver_t *srv,websocketpp::connection_hdl hdl,wsserver_t::message_ptr msg){
wsserver_t::connection_ptr conn=srv->get_con_from_hdl(hdl);
std::cout<<"wsmsg:"<<msg->get_payload();
std::string rsp="client say:"+msg->get_payload();
conn->send(rsp,websocketpp::frame::opcode::text);
}
int main(){
 // 使⽤websocketpp库创建服务器
 
wsserver_t wssrv;
 // 设置websocketpp库的⽇志级别
 wssrv.set_access_channels(websocketpp::log::alevel::none);
// all表⽰打印全部级别⽇志
 
// none表⽰什么⽇志都不打印
 /*初始化asio*/ 
wssrv.init_asio();
wssrv.set_reuse_addr(true);
 // 注册http请求的处理函数
 
wssrv.set_http_handler(std::bind(http_callback, &wssrv,std::placeholders::_1));
 // 注册websocket请求的处理函数
wssrv.set_open_handler(std::bind(wsopen_callback, &wssrv,std::placeholders::_1));
 wssrv.set_close_handler(std::bind(wsclose_callback, &wssrv,std::placeholders::_1));
 wssrv.set_message_handler(std::bind(wsmsg_callback, &wssrv,std::placeholders::_1,std::placeholders::_2));
 // 监听8888端⼝
 
wssrv.listen(8080);
 // 开始接收tcp连接
 
wssrv.start_accept();
 // 开始运⾏服务器
wssrv.run();
 return 0;
 }
